package com.mezizy.ifaner;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.mezizy.ifaner.global.Config;
import com.mezizy.ifaner.global.Global;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static com.mezizy.ifaner.global.Config.*;
import static com.mezizy.ifaner.global.Global.sendGcmRegId;


public class MainActivity extends ActionBarActivity {
    ImageView tabBtn01;
    ImageView tabBtn02;
    ImageView tabBtn03;

    static MainActivity instance;


    /**
     * Substitute you own sender ID here. This is the project number you got
     * from the API Console, as described in "Getting Started."
     */
    String SENDER_ID = "682493270982";

    /**
     * Tag used on log messages.
     */
    static final String TAG = "GCM Demo";

    GoogleCloudMessaging gcm;
    AtomicInteger msgId = new AtomicInteger();
    Context context;
    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;


    public static MainActivity getInstance() {
        return instance;
    }

    public static void setInstance(MainActivity instance) {
        MainActivity.instance = instance;
    }

    public MainActivity() {
        super();
        setInstance(this);

    }



    public void btnTabClick(View v) {

        switch (v.getId()) {
            case R.id.tabLayoutStores:
                mViewPager.setCurrentItem(0);

                break;
            case R.id.tabLayoutOrders:
                mViewPager.setCurrentItem(1);

                break;
            case R.id.tabLayoutSelfInf:
                mViewPager.setCurrentItem(2);

                break;

            default:
                break;

        }

    }

    private ViewPager mViewPager;
    private FragmentPagerAdapter mAdapter;

    private List<Fragment> mFragments = new ArrayList<Fragment>();


    public void resetBtn() {
        tabBtn01.setImageResource(R.drawable.main_tab_store_release);
        tabBtn02.setImageResource(R.drawable.main_tab_orders_release);
        tabBtn03.setImageResource(R.drawable.main_tab_self_release);
        switch (mViewPager.getCurrentItem()) {
            case 0:
                tabBtn01.setImageResource(R.drawable.main_tab_store_pressed);
                StoreListTab.startAsync();
                break;
            case 1:
                tabBtn02.setImageResource(R.drawable.main_tab_orders_pressed);
                OrdersTab.startAsync();
                break;
            case 2:
                tabBtn03.setImageResource(R.drawable.main_tab_self_pressed);
                SelfInformationTab.startGetUserInf();
                break;


        }

    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
//        android.os.Process.killProcess(android.os.Process.myPid());
//        System.exit(0);
//        Global.showToast("为什么不行！");
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
        System.exit(0);
    }


    @Override
    protected void onStart() {
        super.onStart();
        Global.activityLogInCheck(this);
        if (!(getIntent() ==null))
        Log.i(this.getClass().getName(),getIntent().toString());

        if ((getIntent() != null) && getIntent().getBooleanExtra(INTENT_MSG_ORDER_STATE_CHANGED,false)){
            mViewPager.setCurrentItem(1);
        }


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Global.appContext = getApplicationContext();
        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);

        context = getApplicationContext();
        // Check device for Play Services APK. If check succeeds, proceed with GCM registration.
        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(context);

            //TODO 之后加上 if (regid.isEmpty())
                registerInBackground();

        } else {
            Log.i(TAG, "No valid Google Play Services APK found.");
        }




        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        tabBtn01 = (ImageView) findViewById(R.id.tabStores);
        tabBtn02 = (ImageView) findViewById(R.id.tabOrders);
        tabBtn03 = (ImageView) findViewById(R.id.tabSelfInf);

        initView();

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mFragments.get(arg0);
            }
        };

        mViewPager.setAdapter(mAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            private int currentIndex;

            @Override
            public void onPageSelected(int position) {
                resetBtn();
                currentIndex = position;


            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

    }

    private void initView() {

        StoreListTab storeListTab = new StoreListTab();
        OrdersTab ordersTab = new OrdersTab();
        SelfInformationTab selfInformationTab = new SelfInformationTab();

        mFragments.add(storeListTab);
        mFragments.add(ordersTab);
        mFragments.add(selfInformationTab);
    }
    @Override
    protected void onStop() {
        super.onStop();
        Global.dismissProgress(this);
    }

    /**
     * Registers the application with GCM servers asynchronously.
     * <p>
     * Stores the registration ID and the app versionCode in the application's
     * shared preferences.
     */
    String regid;
    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regid = gcm.register(SENDER_ID);
                    msg = "Device registered, registration ID=" + regid;

                    // You should send the registration ID to your server over HTTP, so it
                    // can use GCM/HTTP or CCS to send messages to your app.
                    sendRegistrationIdToBackend(regid);

                    // For this demo: we don't need to send it because the device will send
                    // upstream messages to a server that echo back the message using the
                    // 'from' address in the message.

                    // Persist the regID - no need to register again.
                    storeRegistrationId(context, regid);
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                    // If there is an error, don't just keep trying to register.
                    // Require the user to click a button again, or perform
                    // exponential back-off.
                }
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                //mDisplay.append(msg + "\n");
            }
        }.execute(null, null, null);
    }
    /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    /**
     * @return Application's {@code SharedPreferences}.
     */
    private SharedPreferences getGcmPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.
        return getSharedPreferences(MainActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }
    /**
     * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
     * messages to your app. Not needed for this demo since the device sends upstream messages
     * to a server that echoes back the message using the 'from' address in the message.
     */
    private void sendRegistrationIdToBackend(final String regId) {
        Log.i(TAG,regId);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    sendGcmRegId(regId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        // Your implement
        // ation here.
    }

    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }

    /**
     * Stores the registration ID and the app versionCode in the application's
     * {@code SharedPreferences}.
     *
     * @param context application's context.
     * @param regId registration ID
     */
    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGcmPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }

    /**
     * Gets the current registration ID for application on GCM service, if there is one.
     * <p>
     * If result is empty, the app needs to register.
     *
     * @return registration ID, or empty string if there is no existing
     *         registration ID.
     */
    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGcmPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

}
